/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2019年1月7日
 */

package com.massyframework.beanskin.spring.beancontext;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;

import com.massyframework.beanskin.assembly.Assembly;

/**
 *
 */
public final class WebApplicationContextFactory
        extends AbstractApplicationContextFactory<AbstractRefreshableWebApplicationContext> {

    /**
     * 构造方法
     */
    public WebApplicationContextFactory() {
    }

    /**
     * 根据<code>assembly</code>创建Spring 应用程序上下文
     *
     * @param assembly    {@link Assembly}, 装配件
     * @param initializer {@link ApplicationContextInitializer}, 应用程序上下文初始化器
     * @return {@link AbstractRefreshableWebApplicationContext}
     */
    @Override
    public AbstractRefreshableWebApplicationContext createApplicationContext(Assembly assembly,
    		ApplicationContextInitializer<AbstractRefreshableWebApplicationContext> initializer) {
        Class<?>[] annoTypes = this.getAnnotationTypes(assembly);
        AbstractRefreshableWebApplicationContext result =
                annoTypes.length != 0 ?
                        new AnnotationConfigWebApplicationContext() :
                        new XmlWebApplicationContext();
        if (initializer != null){
            initializer.initialize(result);
        }

        if (result instanceof DefaultResourceLoader) {
        	((DefaultResourceLoader)result).setClassLoader(assembly.getModuleClassLoader());
        }
        if (result instanceof AnnotationConfigWebApplicationContext){
            ((AnnotationConfigWebApplicationContext)result).register(annoTypes);
        }else{
            ((XmlWebApplicationContext)result).setConfigLocations(this.getConfigLocations(assembly));
        }
        return result;
    }
}
